import React from 'react';
import {
    Box,
    Button,
    Card,
    CardContent,
    Dialog,
    Divider,
    FormControl,
    Grid,
    IconButton,
    InputAdornment,
    InputLabel,
    MenuItem,
    Select,
    TextField,
    Tooltip,
    Typography
} from "@mui/material";
import {Done, RestartAlt} from "@mui/icons-material";
import LoadingButton from "@mui/lab/LoadingButton";
import CircularProgress from "@mui/material/CircularProgress";
import ToggleButton from "@mui/material/ToggleButton";
import PendingIcon from "@mui/icons-material/Pending";
import PaidIcon from "@mui/icons-material/Paid";
import ToggleButtonGroup from "@mui/material/ToggleButtonGroup";
import DialogTitle from "@mui/material/DialogTitle";
import CloseIcon from "@mui/icons-material/Close";

import {save} from "../../api/finance/order";
import {alert} from "../common/alert";

const defaultForm = Object.freeze({
    id: 0,
    schoolId: 0,
    courseId: 0,
    parentId: 0,
    studentId: 0,
    amount: 0,
    paid: true,
    grouped: false,
    completed: false,
});

function CreateOrder({open, onClose, courses, parents}) {

    const [form, setForm] = React.useState({...defaultForm});
    const [submitting, setSubmitting] = React.useState(false);

    const [students, setStudents] = React.useState([]);

    const handleChange = (event) => {
        const {name, value} = event.target;

        if (name === 'courseId' && value !== '0') {
            const course = courses.find(e => e.id === value);
            setForm({...form, courseId: value, amount: course.price * course.lessonCount});
        } else if (name === 'parentId') {
            const parent = parents.find(e => e.id === value);
            const children = parent?.children || [];
            const _children = [...children, parent];
            setStudents(_children);

            setForm({...form, parentId: value, studentId: _children[0].id});
        } else {
            setForm({...form, [name]: value});
        }
    }

    const handleSubmit = (event) => {
        event.preventDefault();

        setSubmitting(true);
        save(form).then((data) => {
            setSubmitting(false);

            if (data) {
                setForm({...defaultForm});
                alert('订单创建成功');
            }
        });
    }

    function handleClose(event, reason) {
        event.stopPropagation();
        if (reason !== 'backdropClick' && reason !== 'escapeKeyDown') {
            onClose();
        }
    }

    return (
        <Dialog open={open} onClose={handleClose}>
            <DialogTitle sx={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
                <Typography variant="title">新增订单</Typography>
                <IconButton onClick={onClose}><CloseIcon/></IconButton>
            </DialogTitle>

            <Card raised sx={{width: '480px', padding: 3, boxSizing: 'border-box'}}>
                <CardContent>
                    <form onSubmit={handleSubmit}>
                        <Box display="flex" flexDirection="column" gap={2}>

                            <FormControl fullWidth>
                                <InputLabel>课程</InputLabel>
                                <Select value={form.courseId} label="课程" name="courseId" onChange={handleChange}>
                                    <MenuItem value={0} disabled={true}>选择课程</MenuItem>
                                    <Divider/>
                                    {courses.filter(e => e.visible)
                                        .map(e => <MenuItem key={e.id} value={e.id}>{e.name}</MenuItem>)}
                                </Select>
                            </FormControl>

                            <Grid container spacing={2}>
                                <Grid item xs={6}>
                                    <FormControl fullWidth>
                                        <InputLabel>付款人</InputLabel>
                                        <Select value={form.parentId} label="付款人" name="parentId"
                                                onChange={handleChange}>
                                            <MenuItem value={0} disabled={true}>选择付款人</MenuItem>
                                            <Divider/>
                                            {parents.map(e => <MenuItem key={e.id} value={e.id}>{e.name}</MenuItem>)}
                                        </Select>
                                    </FormControl>
                                </Grid>

                                <Grid item xs={6}>
                                    <FormControl fullWidth disabled={students.length <= 1}>
                                        <InputLabel>学员</InputLabel>
                                        <Select value={form.studentId} label="学员" name="studentId"
                                                onChange={handleChange}>
                                            <MenuItem value={0} disabled={true}>选择学员</MenuItem>
                                            {students.map(e => <MenuItem key={e.id} value={e.id}>{e.name}</MenuItem>)}
                                        </Select>
                                    </FormControl>
                                </Grid>
                            </Grid>

                            <ToggleButtonGroup exclusive={true} name="paid" value={form.paid}
                                               onChange={(_, newValues) => {
                                                   setForm({...form, paid: newValues});
                                               }}>
                                <Tooltip title="未支付" placement="top" arrow>
                                    <ToggleButton value={false}><PendingIcon/></ToggleButton>
                                </Tooltip>
                                <Tooltip title="已支付" placement="top" arrow>
                                    <ToggleButton value={true}><PaidIcon/></ToggleButton>
                                </Tooltip>
                            </ToggleButtonGroup>

                            <TextField label="订单金额" name="amount"
                                       InputProps={{
                                           endAdornment: <InputAdornment position="end">分</InputAdornment>,
                                       }}
                                       value={form.amount} onChange={handleChange}/>

                            <Box>
                                <Button
                                    variant="contained"
                                    color="primary"
                                    startIcon={<RestartAlt/>}
                                    sx={{marginTop: "16px", mr: 2}}
                                    onClick={() => setForm({...defaultForm})}
                                >清空</Button>

                                <LoadingButton
                                    type="submit"
                                    disabled={submitting || form.courseId === 0 || form.parentId === 0 || form.amount < 1 || form.studentId === 0 || form.paid === null}
                                    variant="contained"
                                    color="primary"
                                    startIcon={<Done/>}
                                    sx={{marginTop: "16px"}}
                                    loadingIndicator={<CircularProgress color="inherit" size={24}/>}
                                    loading={submitting}
                                >提交</LoadingButton>
                            </Box>
                        </Box>
                    </form>
                </CardContent>
            </Card>
        </Dialog>
    );
}

export default CreateOrder;
